const app = getApp()
Page({
  data: {
    stuId: '',
    topicId: '',
    stuXx: '',
    sqRea: '',
    loading: false,
    disabled: false,
    from: ''
  },
  onLoad: function(options) {
    if (options.from == 'appstu') {
      this.setData({
        from: 'appstu',
        stuId: options.stuId,
        topicId: options.topicId,
        topicName: options.ktmc
      })
    }
    if (options.from == 'ktgl') {
      this.setData({
        from: 'ktgl',
        stuId: options.stuId
      })
    }
  },
  onShow: function() {
    const that = this
    if (that.data.from == 'ktgl') {
      wx.cloud.database({
        env: 'gtss-2b1812'
      }).collection('Student').doc(that.data.stuId).get().then(res => {
        that.setData({
          stuXx: res.data
        })
      })
    }
    if (that.data.from == 'appstu') {
      wx.cloud.database({
        env: 'gtss-2b1812'
      }).collection('Student').doc(that.data.stuId).get().then(res => {
        that.setData({
          stuXx: res.data
        })
      })
      wx.cloud.database({
        env: 'gtss-2b1812'
      }).collection('Option').where({
        topicId: that.data.topicId,
        userId: that.data.stuId
      }).get().then(res => {
        that.setData({
          sqRea: res.data[0].sqRea
        })
      })
    }
  },
  funAgree: function() {
    const that = this
    that.setData({
      loading: false,
      disabled: false
    })
    wx.cloud.database({
      env: 'gtss-2b1812'
    }).collection('Topic').where({
      teaId: app.globalData.userId,
      ktzt: 1
    }).count().then(res => {
      wx.cloud.callFunction({
        name: 'applyAgree',
        data: {
          topicNumb: res.total,
          maxStuNumb: app.globalData.teaStumax,
          teaId: app.globalData.userId,
          teaName: app.globalData.userName,
          stuId: that.data.stuId,
          stuName: that.data.stuXx.stuName,
          topicId: that.data.topicId,
          topicName: that.data.topicName
        }
      }).then(res => {
        if (res.result.result == 1) {
          wx.showToast({
            title: '课题分配成功！',
            icon: 'success',
            duration: 2000
          })
          that.setData({
            loading: false
          })
          setTimeout(function() {
            that.setData({
              disabled: false
            })
          }, 2500)
          setTimeout(function() {
            wx.navigateBack({
              delta: 2
            })
          }, 2500)
        }
        if (res.result.result == 0) {
          wx.showToast({
            title: '课题分配失败！',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            loading: false
          })
          setTimeout(function() {
            that.setData({
              disabled: false
            })
          }, 2000)
        }
      })
    })
  }
})